package com.hu.book.config;

import com.hu.book.dao.UserDao;
import com.hu.book.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @author xh
 */
@Service
@Qualifier("airUserDetailsService")
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {

        Optional<User> optionalUser = userDao.findByUsername(name);
        User user = optionalUser.get();
        if (optionalUser.get() == null) {
            throw new BadCredentialsException("user '" + name + " 'not find");
        }
        List<GrantedAuthority> authorityList =
                AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_" + optionalUser.get().getRole());
        return new org.springframework.security.core.userdetails.User(name, user.getPassword(), true, true, true, true, authorityList);
    }
}
